﻿using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using System.Linq.Expressions;

namespace Nantianmen.EntityFrameworkCore
{

    public class DateTimeOffsetUtcConverter : ValueConverter<DateTimeOffset, DateTimeOffset>
    {
        static readonly TimeSpan ZeroOffset = TimeSpan.Zero;

        static readonly Expression<Func<DateTimeOffset, DateTimeOffset>> ConvertToUTC =
            (DateTimeOffset time) => time.Offset == ZeroOffset ? time : time.ToOffset(ZeroOffset);

        static readonly Expression<Func<DateTimeOffset, DateTimeOffset>> ConvertFromUTC =
            (DateTimeOffset time) => time.Offset != ZeroOffset ? time : time.ToLocalTime();

        public DateTimeOffsetUtcConverter() : base(ConvertToUTC, ConvertFromUTC)
        {

        }
    }
}
